<template>
    <div class="contain">
        <div class="header">
           <p v-show="!information.voteId">新建投票</p>
           <p v-show="!!information.voteId">编辑投票</p>
           <el-button class="link" type="primary">
                <router-link to="/" style="color: #fff;">返回</router-link>
           </el-button>
       </div>
       <div class="main">
            <el-form :model="information" :rules="rules" ref="information" label-width="150px" class="">
                <el-form-item label="投票ID:" prop="voteId" v-show="!!information.voteId">
                    <div class="item-value" >{{information.voteId}}</div>
                </el-form-item>
                <el-form-item label="投票主题:" prop="voteTitle">
                    <el-input v-model="information.voteTitle" :readonly="!!information.voteId" placeholder="请输入投票主题"></el-input>
                </el-form-item>
                <el-form-item label="投票开始日期:" prop="voteStartTime">
                    <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" :readonly="!!information.voteId" v-model="information.voteStartTime"  type="datetime"  placeholder="选择日期时间"></el-date-picker>
                </el-form-item>
                <el-form-item label="投票截止日期:" prop="voteEndTime">
                    <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" :readonly="!!information.voteId" v-model="information.voteEndTime"  type="datetime"  placeholder="选择日期时间"></el-date-picker>
                </el-form-item>
                <el-form-item label="投票主题介绍:" prop="voteIntroduction" >
                    <el-input style="width: 500px; " type="textarea" autosize v-model="information.voteIntroduction" ></el-input>
                </el-form-item>
                <el-form-item label="设置主题类别:" prop="voteCategory">
                    <el-select filterable v-model='information.voteCategory'  placeholder='-请设置类别-'>
                        <el-option   v-for="item in categoryList"   :key="item.key"   :label="item.value"  :value="item.key"></el-option>
                    </el-select>
                </el-form-item> 
                <el-form-item label="上传主题封面图片:" prop="voteCoverAttachmentId">
                    <el-upload class="avatar-uploader" 
                        :action="this.upLoadUrl"   
                        :show-file-list="false"   
                        :on-success="handleAvatarSuccess"   
                        :before-upload="beforeAvatarUpload">   
                        <img v-if="information.voteCoverUrl" :src="information.voteCoverUrl" class="avatar">   
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i> 
                        <div class="up-tips">建议上传封面尺寸：750*360,图片大小不超过2M</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="投票代币名称:" prop="voteAssetCode">
                    <el-input v-model="information.voteAssetCode" :readonly="!!information.voteId" placeholder="请输入投票代币名称"></el-input>
                </el-form-item>
                <el-form-item label="投票主题属性:" prop="voteOptionType">
                    <div class="item-value" v-show="!!information.voteId" >{{information.voteOptionType == '1' ? "简单投票":"图片投票"}}</div>
                    <el-select v-show="!!!information.voteId" v-model="information.voteOptionType" placeholder="--请选择--">
                        <el-option v-for="item in voteOptionTypeList" :key="item.key" :label="item.value" :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否限定投票:" prop="isLimit" >
                    <div v-show="!!!information.voteId">
                        <el-radio v-model="information.isLimit" label="y">是</el-radio>
                        <el-radio v-model="information.isLimit" label="n">否</el-radio>
                    </div>
                    <div v-show="!!information.voteId">
                         <div class="item-value" v-show="!!information.voteId" >{{information.isLimit == 'y' ? "限定投票":"非限定投票"}}</div>
                    </div>
                </el-form-item>
                
                <el-form-item>
                    <el-button type="primary" @click="submitForm('information')"  :loading="loading">确定</el-button>
                    <el-button @click="resetForm('information')">重置</el-button>
                </el-form-item>
                <div v-show="!!information.voteId">
                    <div class="title" style="display:flex; justify-content:space-between; "><span>投票选项信息</span><span style="margin-right: 30px; "><el-button type="text" style="font-weight: bolder;" @click="information.voteOptionList.push({})">+ 新增投票选项</el-button></span></div>
                    <div class="table_con">
                        <el-table  :data="information.voteOptionList"  style="width: 100%; text-align:center"  :border='true'>
                            <el-table-column  prop="optionContent"    label="选项名称" style="width: 20%;">
                                <template slot-scope="scope" >
                                    <el-input v-show="!scope.row.optionId" v-model="scope.row.optionContent" placeholder="请输入选项名称" style="width: 200px;"></el-input>
                                    <div v-show="scope.row.optionId" style="width: 200px;">{{scope.row.optionContent}}</div>
                                </template>
                            </el-table-column>
                            <el-table-column  prop="optionIntroduction" label="选项介绍">
                                <div class="item-value" ></div>
                                <template slot-scope="scope" v-if="information.voteOptionType == '2'">
                                    <el-input v-model="scope.row.optionIntroduction" v-show="!scope.row.optionId" placeholder="请输入选项介绍" style="width: 200px;"></el-input>
                                    <div v-show="scope.row.optionId" style="width: 200px;">{{scope.row.optionContent}}</div>
                                </template>
                            </el-table-column>
                            <el-table-column  prop="optionCoverUrl" label="图片" >
                                <template slot-scope="scope" v-if="information.voteOptionType == '2'">
                                    <div @click="getIndex(scope.$index)"  > 
                                        <el-upload class="avatar-uploader" 
                                        :action="upLoadUrl"   
                                        :show-file-list="false"   
                                        :on-success="handleAvatarSuccessOption" 
                                        :before-upload="beforeAvatarUpload">   
                                        <img v-if="scope.row.optionCoverUrl" :src="scope.row.optionCoverUrl" class="avatar">   
                                        <i v-else class="el-icon-plus avatar-uploader-icon"></i> 
                                        </el-upload>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column  prop="optionAddress" label="区块链地址" >
                            </el-table-column>
                            <el-table-column  prop="optionId" label="操作" >
                                <template slot-scope="scope">
                                    <el-button type="primary" size="mini" plain @click="confirm(scope.$index)" v-show="!!!scope.row.optionId"  :loading="loading">确定</el-button>
                                    <el-button type="danger" size="mini" plain @click="deleteOption(scope.$index,scope.row.optionId)" :loading="loading">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </el-form>
        </div>
       
    </div>
    

</template>

<script>
let CONSTANT = require('../../constant/constant.js');
let common = require("../../common.js");
import $ from 'jquery'
  export default {
    data() {
        // 校验投票开始时间不能大于投票结束时间
        var validateStartEndTime = (rules,value,callback) =>{
            if(this.information.voteStartTime > this.information.voteEndTime){
                callback(new Error('投票开始时间不能大于投票结束时间')); 
            }else{
                callback();
            }
        };
        var validateVoteAssetCode = (rules,value,callback)=>{
            // 编辑时不校验代币名称
            if(this.show) callback();
            
            let url = CONSTANT.URL.VOTE.CHECKVOTEASSETCODE;
            let dataForm = {
                voteAssetCode:this.information.voteAssetCode
            };
            let data = {
                // searchWord:this.searchWord,
            };
            let param = JSON.stringify(data);
            this.loading = true;
            common.requestAjax(url, param, dataForm, res => {
                this.loading = false;
                // console.log('检查投票代币名称是否已使用----', res);
                if(res.status == 200){ 
                    callback();
                }else{
                    callback(new Error(res.msg));
                }
            });
      }
      return {
        show:'',
        uploadIndex:0,
        upLoadUrl:'',
        categoryList:[],
        information: {},
        isLimitList:[
            {key: 'y',  value: '是'}, 
            {key: 'n', value: '否'},
        ],
        // 投票类型
        voteOptionTypeList:[
            {key: '1',  value: '简单投票'}, 
            {key: '2', value: '图片投票'}, 
        ],
       
        rules: {
           voteTitle: [
             { required: true, message: '请输入投票主题', trigger: 'blur' },
             { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
           ],
           voteStartTime: [
             { required: true, message: '请选择投票开始日期', trigger: 'blur' },
           ],
           voteEndTime: [
             { required: true, message: '请选择投票结束日期', trigger: 'blur' },
             { validator: validateStartEndTime, trigger: 'blur' },
           ],
           voteIntroduction: [
             { required: true, message: '请输入投票主题介绍', trigger: 'blur' },
           ],
           voteCategory: [
             { required: true, message: '请设置主题类别', trigger: 'blur' },
           ],
           voteCoverAttachmentId: [
               { required: true, message: '选择封面图片', trigger: 'blur' },
           ],
           voteAssetCode: [
             { required: true, message: '请输入投票代币名称', trigger: 'blur' },
             { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' },
             { validator: validateVoteAssetCode, trigger: 'blur' },
           ],
           voteOptionType: [
             { required: true, message: '请设置投票主题属性', trigger: 'blur' },
           ],
           isLimit: [
             { required: true, message: '请设置投票限定属性', trigger: 'blur' },
           ],
        },
        loading: false
      };
    },
    mounted() {
        this.information.voteId = this.$router.currentRoute.query.id; // 修改时带上
        // console.log('修改时传递的id',this.information.voteId);
        if(this.information.voteId){
            this.show = true;
        }
        let sessionId = sessionStorage.getItem('sessionId');
        this.upLoadUrl = CONSTANT.URL.SYSTEM.ADMINUPLOADFILE+ '?sessionId='+sessionId;
        this.getVoteCategory();
        if(this.information.voteId){
            this.getVoteDetail();
        }
    },
    methods: {
        // 根据类型获取字典   获取主题类别
        getVoteCategory:function(){
            let url = CONSTANT.URL.DICTIONARY.LOADDICTIONARY
            let dataForm = {
                codeType:'vote_category',
            };
            let data = {
            };
            let param = JSON.stringify(data);
            common.requestAjax(url, param, dataForm, res => {
                this.loading = false;
                let data = res.data.bussData;
                // console.log('查询投票类别----', data);
                let categoryList = [];
                data.forEach(function(item){
                    let categoryObj = {};            
                    categoryObj.key = item.key;
                    categoryObj.value = item.value;
                    categoryList.push(categoryObj);
                })
                this.categoryList = categoryList;
                this.information.loading = false
            });
        },
        getVoteDetail:function(){
            let url = CONSTANT.URL.VOTE.FINDVOTEDETAIL;
            let param = {
               voteId:this.information.voteId
            };
            common.requestAjax(url,param,null,(res)=>{
                this.information = res.data.bussData;
           }) 
        },
        confirm:function(index){
            // console.log('新增投票选项----',optionList);
            let url = CONSTANT.URL.VOTE.SAVEVOTEOPTION
            let param = this.information.voteOptionList[index];
                param.voteId  = this.information.voteId;

            common.requestAjax(url,JSON.stringify(param),null,(res)=>{
                    let data = res;
                    if(200 == data.status) {
                        this.$set(this.information.voteOptionList[index], 'optionId', data.data.bussData.optionId);
                        this.$set(this.information.voteOptionList[index], 'optionAddress', data.data.bussData.optionAddress);
                    } else {
                        this.$message({
                            type: 'error',
                            message: '保存选项失败!'
                        });
                    }
                
            }) 
            
        },
        // 删除投票选项
        deleteOption:function(index,optionId){
            if(!!optionId){
                let url = CONSTANT.URL.VOTE.DELVOTEOPTION
                let param = {
                    optionId:optionId,
                };
                common.requestAjax(url,param,null,(res)=>{
                    let data = res;
                    if(200 == data.status) {
                        this.$message({
                            type: 'success',
                            message: '删除选项成功!'
                        });
                    }
                    // this.getVoteDetail();
                }) 
            }
            this.information.voteOptionList.splice(index,1);
            
        },
        //  单张图片上传  封面
        handleAvatarSuccess(res, file){
            this.$set(this.information, 'voteCoverUrl', URL.createObjectURL(file.raw));
            // console.log('封面res',res);
            if(res.status == 200){
                let data = res.data.bussData;
                this.information.voteCoverAttachmentId = data.fileId;
                // console.log(this.information)
            }
        },
        getIndex(index){
            // console.log('test', index);
            this.uploadIndex = index;
        },
        // 增加投票选项图片上传
        handleAvatarSuccessOption(res, file){
            let index = parseInt(this.uploadIndex);
            // 解决Vue改变数组中对象的属性不重新渲染View this.$set(obj, 'key', value);
            this.$set(this.information.voteOptionList[index], 'optionCoverUrl', URL.createObjectURL(file.raw));
          
            // console.log('投票选项图片res---', res);
            if(res.status == 200){
                let data = res.data.bussData;
                this.information.voteOptionList[index].optionCoverAttachmentId = data.fileId;
            }
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;
            // if (!isJPG) {
            // this.$message.error('上传头像图片只能是 JPG 格式!');
            // }
            if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            // return isJPG && isLt2M;
            return  isLt2M;
        },
        
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
            if (valid) {
                // 保存时键为id
                this.information.id = this.information.voteId;
                this.loading = true;
                let url = CONSTANT.URL.VOTE.SAVEVOTE;
                let data = this.information;
                let param = JSON.stringify(data);
                // console.log('保存表单信息内容',data);
                common.requestAjax(url, param, null, res => {
                    if(res.status == 200) {
                        // console.log('保存返回的id',res.data.bussData);
                        this.information.voteId = res.data.bussData
                        this.getVoteDetail();
                        this.$message({
                            type: 'success',
                            message: '保存投票信息成功!'
                        });
                        this.loading = false;

                        // this.$router.push("/voteList");
                    } else {
                        this.$message({
                            type: 'error',
                            message: res.msg
                        });
                        this.loading = false;
                    }
                });
            } else {
                console.log('error submit!!');
                return false;
            }
        });
        },
        resetForm(formName) {
            console.log('重置',formName);
            this.information.imageUrl = '';
            this.$refs[formName].resetFields();
        },
    },
    
  }
</script>

<style lang="scss" scoped >
@import '/static/bootstrap.css';     
@import '/book/static/bootstrap.css'; 
    .contain {
        margin-bottom: 100px;
        .header{
            height: 46px;
            padding-bottom: 10px;
            border-bottom: 1px solid #dedede;
            p{ float: left;height: 36px;line-height: 36px;margin: 0 0 0 10px;font-size: 18px;}
            .el-button{
                float: right;
                margin-right: 5%
            }
        }
        .main {
            width:80%;
            max-width: 1500px;
            margin: 20px 0 0 40px;
            clear: both;
            .el-input,
            .el-select {
                width: 250px;
            }
            .el-form{
                .el-form-item__label{
                    width: 120px !important;
                }
            }
            .modal-body{
                .note-image-input{
                    display: block;
                }
            }
            .avatar-uploader {
                     .el-upload {
                        cursor: pointer;
                        position: relative;
                        overflow: hidden;
                        .avatar-uploader-icon {
                            font-size: 28px;
                            color: #8c939d;
                            width: 178px;
                            height: 178px;
                            line-height: 178px;
                            text-align: center;
                            border: 1px dashed #d9d9d9 !important;
                            border-radius: 6px;
                            margin-left: 6px;
                        }
                        .avatar {
                            width: 178px;
                            height: 178px;
                            display: block;
                        }
                    }
                    .el-upload:hover {
                        border-color: #20a0ff;
                    }
                    
                }
        }
    }
    
</style>
<style>
     .el-form-item__content{
         margin-left: 120px !important;
     }
     .title{
        padding-left: 20px;
        height: 40px;
        line-height: 40px;
        background-color: #f5f5f5;
        border: 1px solid #dedede;
        font-weight: 600;
    }
</style>

